package com.qf.zyh.dao.Impl;

import com.qf.zyh.dao.ItemDao;
import com.qf.zyh.entity.Item;
import com.qf.zyh.entity.Product;
import com.qf.zyh.util.DBUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ItemDaoImpl implements ItemDao {
    QueryRunner qr = new QueryRunner();

    @Override
    public void addItem(List<Item> items) throws SQLException {
        Object[][] args = new Object[items.size()][];
        String sql = "insert into item values(default,?,?,?,?)";
      //循环遍历添加数据
        for (int i=0;i<items.size();i++){
            //取出数据产生对象
            Item item = items.get(i);
            //根据填写语句，要与sql语句顺序相同
            args[i]=new Object[]{item.getOid(),item.getPid(),item.getIcount(),item.getInum()};
        }
        //batch是批处理方法
        int[] batch = qr.batch(DBUtil.getConnection(), sql, args);
    }

    @Override
    public List<Item> seleid(String oid) throws InvocationTargetException, IllegalAccessException, SQLException {
        List<Map<String, Object>> select = qr.query(DBUtil.getConnection(), "select i.iid,i.oid,i.pid,i.icount,i.inum,p.pid,p.tid,p.pname,p.ptime,p.pimage,p.pprice,p.pstate,p.pinfo from item i inner join product p on i.pid=p.pid where oid=?", new MapListHandler(), oid);
        if (select!=null) {
            List<Item> ltt = new ArrayList<>();
            for (Map<String, Object> map : select) {
                Item it = new Item();
                Product pro = new Product();
                BeanUtils.populate(it,map);
                BeanUtils.populate(pro,map);
                it.setProduct(pro);
                ltt.add(it);
            }
            return ltt;
        }
        return null;
    }
}
